package com.example.gener.rongyundemo.chatroom;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.AnimRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.gener.rongyundemo.R;
import com.example.gener.rongyundemo.customUI.KeyboardLayout;
import com.example.gener.rongyundemo.customUI.SoftKeyInputHidWidget;
import com.jk.myimkit.imkit.RongIM;
import com.jk.myimkit.imkit.fragment.ConversationFragment;

import java.util.List;


import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * 进入这个界面则为进入聊天室
 * 获取到当前聊天室名单,显示在左侧的连表上
 * 点击进入大厅才能收到和发送聊天信息同时打开大厅界面
 * 点击离开大厅则不再收到大厅信息同时关闭大厅界面
 */
public class ChatRoomOneActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView chatRoomRv;
    private CardView cardView;
    private KeyboardLayout kl_main;
    private HandlerThread handlerThread;
    private Handler mHandler;
    private ConversationFragment singleChatFragment;
    private TextView tv_chat_flag;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_chat_room_one);

        init();
        addLayoutListener();
        initReclear();
        handlerThread = new HandlerThread("lalala");
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper());

    }

    private void initReclear() {

    }

    /**
     * 监听键盘状态，布局有变化时，靠scrollView去滚动界面
     */
    private boolean isShowKeyBoard;
    private boolean isChangeLayout = false;
    private RelativeLayout.LayoutParams cardViewOldParam;
    private int beforeHeight;
    private int beforeMarginTop;

    public void addLayoutListener() {
        kl_main.setKeyboardListener(new KeyboardLayout.KeyboardLayoutListener() {
            @Override
            public void onKeyboardStateChanged(boolean isActive, int keyboardHeight) {
                Log.e("onKeyboardStateChanged", "isActive:" + isActive + " keyboardHeight:" + keyboardHeight);

                if (isActive) {
                    if (!isChangeLayout && !isShowKeyBoard) {
                        RelativeLayout.LayoutParams params;
                        cardViewOldParam = (RelativeLayout.LayoutParams) cardView.getLayoutParams();

                        params = cardViewOldParam;
                        beforeHeight = params.height;
                        beforeMarginTop = params.topMargin;
                        int screenHeight = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
                                .getDefaultDisplay().getHeight();
                        int moveDistance = keyboardHeight - (screenHeight - params.height - params.topMargin);
                        params.height = params.height - (moveDistance - params.topMargin);
                        params.topMargin = 0;

                        cardView.setLayoutParams(params);
                        isShowKeyBoard = true;
                        isChangeLayout = true;
                    } else {
                        isChangeLayout = false;
                    }
                } else {
                    if (isShowKeyBoard) {
//                        cardViewOldParam.height = beforeHeight;
                        cardViewOldParam.height = beforeHeight;
                        cardViewOldParam.topMargin = beforeMarginTop;
                        cardView.setLayoutParams(cardViewOldParam);

                        isShowKeyBoard = false;
                    }
                }
            }
        });

    }

    ViewTreeObserver.OnGlobalLayoutListener listener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Log.d("", "");
        }
    };

    /**
     * 弹出软键盘时将SVContainer滑到底
     */
    private void scrollToBottom() {

        ObjectAnimator translationY = new ObjectAnimator().ofFloat(cardView, "translationY", 0, cardView.getBottom() + SoftKeyInputHidWidget.getStatusBarHeight(ChatRoomOneActivity.this));

        AnimatorSet animatorSet = new AnimatorSet();  //组合动画
        animatorSet.playTogether(translationY); //设置动画
        animatorSet.setDuration(100);  //设置动画时间
        animatorSet.start(); //启动

//        sv_main.postDelayed(new Runnable() {
//
//            @Override
//            public void run() {
//                sv_main.smoothScrollTo(0, cardView.getBottom() + SoftKeyInputHidWidget.getStatusBarHeight(ChatRoomOneActivity.this));
////                cardView.scrollTo(0,cardView.getBottom() + SoftKeyInputHidWidget.getStatusBarHeight(ChatRoomOneActivity.this));
//            }
//        }, 100);

    }

    @Override
    protected void onStart() {
        super.onStart();
        RongIM.getInstance().joinChatRoom("Jiang2", 50, new RongIMClient.OperationCallback() {
            @Override
            public void onSuccess() {
                Toast.makeText(ChatRoomOneActivity.this, "Join The ChatRoom Success", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                Toast.makeText(ChatRoomOneActivity.this, "Join The ChatRoom error", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void init() {
        chatRoomRv = findViewById(R.id.rv_chat_member);
        tv_chat_flag = findViewById(R.id.tv_chat_flag);
        findViewById(R.id.btn_enter_into_hall).setOnClickListener(this);
        findViewById(R.id.btn_leave_hall).setOnClickListener(this);
        findViewById(R.id.btn_single_chat).setOnClickListener(this);
        cardView = findViewById(R.id.cardView_chat_room);
        kl_main = findViewById(R.id.kl_main);
        initChatRoomFragment();
        initSingleChatFragment();
        kl_main.getViewTreeObserver().addOnGlobalLayoutListener(listener);
    }


    public static void start(Context context) {
        context.startActivity(new Intent(context, ChatRoomOneActivity.class));
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_single_chat:
//                if (isVisibleSingleChat()) {
//                    hideChatRoom();
//                } else {
                    showSingleRoom();
//                }
                break;
            case R.id.btn_enter_into_hall:
//                RongIM.getInstance().startChatRoomChat(ChatRoomOneActivity.this,"Jiang",false);
//                MyConversationFragment fragment = new MyConversationFragment();
//
//                Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
//                        .appendPath("rc_conversation").appendPath(Conversation.ConversationType.CHATROOM.getName().toLowerCase())
//                        .appendQueryParameter(Conversation.ConversationType.CHATROOM.getName(), "true")
//                        .appendQueryParameter("targetId", "Jiang").build();
//
//                fragment.setUri(uri);
//                FragmentTransaction add = getSupportFragmentManager().beginTransaction().add(R.id.fl_chat_hall, fragment);
//                add.commit();

//                if (isVisibleChatRoom()) {
                    showChatRoom();
//                } else {
//                    hideChatRoom();
//                }
                break;

            case R.id.btn_leave_hall:
                if (chatRoomRv.getVisibility() == View.VISIBLE) {

                    Animation animation = AnimationUtils.loadAnimation(this, R.anim.fragment_slide_out_from_left);
                    chatRoomRv.clearAnimation();
                    chatRoomRv.setAnimation(animation);
                    animation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            chatRoomRv.setVisibility(View.GONE);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });


                } else {
                    chatRoomRv.setVisibility(View.VISIBLE);
                    chatRoomRv.setAnimation(AnimationUtils.loadAnimation(this, R.anim.fragment_slide_in_from_left));
                }
//                android.app.AlertDialog.Builder alter = new AlertDialog.Builder(ChatRoomOneActivity.this);
//                alter.setTitle("聊天室连接异常");
//                alter.setMessage("是否重连").setPositiveButton("重连", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                    }
//                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                    }
//                });
//                alter.show();
                break;
        }
    }


    /**
     * 初始化聊天室
     */
    ConversationFragment chatRoomFragment;

    private void initChatRoomFragment() {
        chatRoomFragment = new ConversationFragment();
        Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                .appendPath("rc_conversation").appendPath(Conversation.ConversationType.CHATROOM.getName().toLowerCase())
                .appendQueryParameter(Conversation.ConversationType.CHATROOM.getName(), "true")
                .appendQueryParameter("targetId", "1").build();
        chatRoomFragment.setUri(uri);

    }

    /**
     * 是否显示ChatRoom
     *
     * @return
     */
    private boolean isHiddenChatRoom(Fragment fragment) {


        return fragment.isVisible();
    }

    /**
     * 显示聊天室
     */
    private void showChatRoom(Fragment showFragment) {
        cardView.setVisibility(View.VISIBLE);

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
//        fragmentTransaction.setCustomAnimations(R.anim.fragment_slide_in_from_left,R.anim.fragment_slide_out_from_left);
        if (!showFragment.isAdded()) {
            fragmentTransaction.add(R.id.fl_chat_hall, showFragment, "ChatRoomFragment").commit();
        } else {
            fragmentTransaction.show(showFragment).commit();
        }

    }




    private boolean isVisibleChatRoom() {
//        if (chatRoomFragment.getIsOnCreate()){
//
//            return chatRoomFragment.isVisible();
//        }else {
            return false;
//        }
    }

//    private boolean isVisibleSingleChat() {
//
//    }

    private void showChatRoom() {
//        hideChatSingle();
        tv_chat_flag.setVisibility(View.VISIBLE);
        tv_chat_flag.setText("聊天室");
        cardView.setVisibility(View.VISIBLE);

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (!chatRoomFragment.isAdded()) {
            fragmentTransaction.add(R.id.fl_chat_hall, chatRoomFragment, "ChatRoomFragment").commit();
        } else {
            fragmentTransaction.show(chatRoomFragment).commit();
        }
    }


    private void showSingleRoom() {
//        hideChatRoom();
        tv_chat_flag.setVisibility(View.VISIBLE);
        tv_chat_flag.setText("单聊");
        cardView.setVisibility(View.VISIBLE);

//        switchChatFragment(chatRoomFragment, singleChatFragment);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (!singleChatFragment.isAdded()) {
            fragmentTransaction.add(R.id.fl_chat_single, singleChatFragment, "ChatSingleFragment").commit();
        } else {
            fragmentTransaction.show(singleChatFragment).commit();
        }

    }

    private void initSingleChatFragment() {
        singleChatFragment = new ConversationFragment();
        Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                .appendPath(Conversation.ConversationType.PRIVATE.getName().toLowerCase())
                .appendQueryParameter("targetId", "jiangdashuai").build();//和userId为1的聊天
        singleChatFragment.setUri(uri);
    }

    private void switchChatFragment(Fragment hideFragment, Fragment showFragment) {

        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (!showFragment.isAdded()) {
            getSupportFragmentManager().beginTransaction().hide(hideFragment).add(R.id.fl_chat_hall, showFragment).commit();
        } else {
            getSupportFragmentManager().beginTransaction().hide(hideFragment).show(showFragment).commit();
        }
    }

    /**
     * 隐藏聊天室
     */
    private void hideChatRoom() {
//        cardView.setVisibility(View.GONE);
//        cardView.setAnimation(AnimationUtils.loadAnimation(this, R.anim.fragment_slide_out_from_left));

//        FragmentManager supportFragmentManager = getSupportFragmentManager();
//        Fragment chatRoomFragment = supportFragmentManager.findFragmentByTag("ChatRoomFragment");
//        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
////        fragmentTransaction.setCustomAnimations(R.anim.fragment_slide_in_from_left,R.anim.fragment_slide_out_from_left);
//        fragmentTransaction.hide(chatRoomFragment).commit();
        tv_chat_flag.setVisibility(View.GONE);
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        Fragment chatRoomFragment = supportFragmentManager.findFragmentByTag("ChatRoomFragment");
        if (chatRoomFragment==null){
            return;
        }
        supportFragmentManager.beginTransaction().hide(chatRoomFragment).commit();
        cardView.setVisibility(View.GONE);

    }

    private void hideChatSingle(){
        tv_chat_flag.setVisibility(View.GONE);
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        Fragment chatRoomFragment = supportFragmentManager.findFragmentByTag("ChatSingleFragment");

        supportFragmentManager.beginTransaction().hide(chatRoomFragment).commit();
        cardView.setVisibility(View.GONE);
    }
}
